﻿using System;
using System.Collections.Generic;

namespace StateMachine
{
    public abstract class FiniteStateMachine<T>
        where T : struct
    {
        private readonly StateMachineContext<T> context;
        private readonly Dictionary<T, StateHandler<T>> stateHandlers;

        public FiniteStateMachine(StateMachineContext<T> context)
        {
            this.stateHandlers = new Dictionary<T, StateHandler<T>>();
            this.context = context;
        }

        protected StateMachineContext<T> Context
        {
            get
            {
                return this.context;
            }
        }

        protected void RegisterStateHandler(T state, StateHandler<T> handler)
        {
            this.stateHandlers[state] = handler;
        }

        public void HandleInput(object input)
        {
            StateHandler<T> handler;
            if (!this.stateHandlers.TryGetValue(this.Context.State, out handler))
            {
                throw new NotRegisteredStateException(String.Format("State {0} must be registered through the RegisterStateHandler method!", this.Context.State));
            }

            handler.HandleInput(input);
        }
    }
}
